<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\base\BaseController;
use app\home\validate\EnterpriseCheck;
use app\home\validate\ItemCheck;
use app\home\validate\NewUserCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class User extends BaseController
{
    /**
     * 员工管理
     */
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

            if($eid > 0){
                $where[] = ['eid' , '=' , $eid];
            }
            if(!empty($param['status'])){
                $where[] = ['status' , '=' , $param['status']];
            }else{
                $where[] = ['status', '>=', 0];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content = Db::name('User')
                ->order('eid asc , create_time desc')
                ->where($where)
                ->paginate($rows, false, ['query' => $param])->toArray();

            foreach($content['data'] as $key => &$value){
                $value['fmt_employment_time'] = !empty($value['employment_time']) && $value['employment_time'] > 0 ? date('Y-m-d' , $value['employment_time']) : '' ;

                $deparment = Db::name('Enterprise')->where(['id'=>$value['eid']])->find();
                $value['d_name'] = $deparment['title'] ?? '系统管理员';

                //查询部门
                $depart = Db::name('EnterpriseDepartment')->where(['id' => $value['did']])->find();
                $value['depart_name'] = $depart['title'] ?? '';
            }

            return table_assign(0, '', $content);
        } else {

            return view();
        }
    }

    /**
     * 添加/编辑员工员工
     */
    public function add()
    {
        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;
        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(NewUserCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['update_time'] = time();
                $param['employment_time'] = strtotime($param['employment_time']);
                $res = Db::name('User')->strict(false)->field(true)->update($param);
                if ($res) {
                    add_log('edit', $param['id'], $param);
                }
                return to_assign();
            } else {
                try {
                    validate(NewUserCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['create_time'] = time();
                $param['employment_time'] = strtotime($param['employment_time']);
                $insertId = Db::name('User')->strict(false)->field(true)->insertGetId($param);
                if ($insertId) {
                    add_log('add', $insertId, $param);
                }
                return to_assign();
            }
        }else {

            if($this->eid > 0){
                $enterprise = Db::name('Enterprise')->where('id',$this->eid)->where('status', '>=', 0)->order('create_time asc')->select();
            }else{
                $enterprise = Db::name('Enterprise')->where('status', '>=', 0)->order('create_time asc')->select();
            }

            View::assign('enterprise', $enterprise);
            View::assign('eid', $this->eid);

            $detail = [];
            if (!empty($param['id']) && $param['id'] > 0) {
                $detail = Db::name('User')->where(['id' => $param['id']])->find();

                $detail['fmt_employment_time'] = !empty($detail['employment_time']) && $detail['employment_time'] > 0 ? date('Y-m-d' , $detail['employment_time']) : '' ;
                $detail['fmt_end_time'] = !empty($detail['end_time']) && $detail['end_time'] > 0 ? date('Y-m-d' , $detail['end_time']) : '' ;

                $eid = $detail['eid'];
            }

            $department = set_recursion(get_enterprise_department(['eid'=>$eid]));
            View::assign('department', $department);
            View::assign('detail', $detail);

            return view();

        }
    }

    /**
     * 操作员工
     * @return \json
     */
    public function opertion()
    {
        $param = get_params();
        $res = Db::name('Item')->strict(false)->field('id,status')->update($param);
        if ($res) {
            if($param['status'] == 1){
                add_log('disable', $param['id'], $param);
            }
            else if($param['status'] == 2){
                add_log('open', $param['id'], $param);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    //删除
    public function delete()
    {
        $id = get_params("id");
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        $data['delete_time'] = time();
        if (Db::name('User')->update($data) !== false) {
            add_log('delete', $id, $data);
            return to_assign(0, "操作成功");
        } else {
            return to_assign(1, "操作失败");
        }
    }

    /**
     * 生成员工编号
     * @param $param
     * @return string
     */
    protected function code($param){

        return 'XM-'.$param['eid'].'-'.time();

    }

}
